<template>
  <base-breadcrumb :breadcrumb="!isAudit">
    <a-form-model :model="form" ref="ruleForm"
                          :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
                          :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
      <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
        <title-name  title="查看分包商考察"></title-name>
        <div>
          <a-tabs ref="tabs" v-model="nextSteps" @change="callback" >
            <a-tab-pane key="1" tab="基本信息" >
              <title-name title="考察分包商"></title-name>
              <a-row :gutter="24" >
                <a-col :md="8" :sm="8">
                  <a-form-model-item
                          label="分包商名称" prop="subcontractorName">
                    <BaseInput v-model="form.subcontractorName" disabled placeholder="请输入" ></BaseInput>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24" >
                <a-col :md="8" :sm="8">
                  <a-form-model-item
                          label="考察类型" prop="investigateType">
                    <a-select :getPopupContainer="getPopupContainer" disabled v-model="form.investigateType"  placeholder="请选择" default-value="" @change="changeType">
                      <a-select-option value="1">服务类分包商考察</a-select-option>
                      <a-select-option value="2">甲指分包商考察</a-select-option>
                      <a-select-option value="3">劳务/专业分包商考察</a-select-option>
                    </a-select>
                   </a-form-model-item>
                </a-col>
                <a-col :md="10" :sm="10">
                  <a-form-model-item label="分公司" prop="branchCompanyId">
                  <a-select :getPopupContainer="getPopupContainer" disabled   v-model="form.branchCompanyId" placeholder="请选择" >
                    <a-spin v-if="loading" slot="notFoundContent" size="small" />
                    <a-select-option v-for="item in companyList" :key="item.id" :value="item.id">{{item.name}}
                    </a-select-option>
                  </a-select>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :md="24" :sm="24">
                  <a-form-model-item
                          label="分包商类型" prop="subcontractorsType">
                    <a-tree-select
                      :getPopupContainer="getPopupContainer"
                      v-model="form.subcontractorsType"
                      style="width: 100%"
                      disabled
                      multiple
                      :dropdown-style="{ maxHeight: '500px', overflow: 'auto' }"
                      :replace-fields="{children:'children', key:'id', value: 'id', title: 'name'}"
                      :tree-data="invesList"
                      placeholder="请选择"
                      >
                    </a-tree-select>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <title-name title="考察小组"></title-name>
                  <!-- <add-group></add-group> -->

              <div>
                <a-row>

                  <a-table
                          :columns="columns" bordered
                          :rowKey="(record) => record.employeeId || record.id"
                          :data-source="memberList">

                    <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
                    <template slot="type" slot-scope="text,record">
                      <span v-if="record.type">{{ ['组长', '成员'][record.type - 1] }}</span>
                    </template>

                    <span slot="action" slot-scope="text, record,index">
                          <template>
                          <!-- <a    disabled    @click="handleEditGroup(record,index)">编辑</a> -->
                          </template>
                        </span>
                  </a-table>
                </a-row>
              </div>


              <a-button style="float:right;margin:10px" @click="nextStep()" type="primary">下一步</a-button>
            </a-tab-pane>
            <a-tab-pane key="2" tab="考察信息" >
              <!-- 服务 -->
              <service
                  @submitNext="getsubmitNext" 
                  ref="serverRef" 
                  :serviceList ="serviceList" 
                  v-if="(form.investigateType=='1' || form.investigateType =='服务类分包商考察')"
                  @validChanged="handleValidChanged"
                  disabled
                  ></service>
              <!-- 甲指 -->
              <Fingernail
                  @submitNextSteps="getsubmitNextSteps"  
                  ref="serverRef" 
                  :fingernailList="fingernailList" 
                  v-if="(form.investigateType=='2' || form.investigateType =='甲指分包商考察') "
                  @validChanged="handleValidChanged"
                  disabled
                  ></Fingernail>
              <!-- 劳务 -->
              <labour
               @submitNextStep="getsubmitNextStep"  
               ref="serverRef" :labourList="labourList" 
               v-if="form.investigateType=='3' || form.investigateType =='劳务/专业分包商考察'"
               @validChanged="handleValidChanged"
               disabled
               ></labour>
              <!-- <a-button style="float:right;" @click="nextStep()" type="primary">下一步</a-button> -->
            </a-tab-pane>

            <a-tab-pane key="3" tab="附件上传">
            <u-table
              :uploadArrys="fileArrysDataList"
              businessCode="PM09"
              :reqMethod="reqMethod"
              :listUrl="listUrl"
              :isShow="false"
              :uploadList="uploadList"
              :businessId="id"
              :deleteUrl="deleteUrl"
              :refreshAfterUpload="false"
              @fileArrysData="fileArrysData"
            ></u-table>
            </a-tab-pane>
          </a-tabs>
        </div>
      </a-card>
    </a-form-model>
    <div v-if="!isConsultation" style="float:right" class="page-btn-right-top">
      <a-button class="button ml12" type="primary" @click="goBack">关闭</a-button>
    </div>
  </base-breadcrumb>
</template>

<script>
  import { getAttachment } from '@/api/commons'
  import { STable, Ellipsis } from '@/components'
  import {
    basicInformation,
    getGroup,
    addbasicInformation,
    editbasicInformation,
    getbasicInformation ,
    addLabourBasic,
    getInvestigateType,
    updateSubStatus,
    editfingernailList
     } from '@/api/subcontractors/subcontractors'
  import AddGroup from '@/views/subcontractors/investigate/components/AddGroup'
  import Service from '@/views/subcontractors/investigate/components/Service'
  import Fingernail from '@/views/subcontractors/investigate/components/Fingernail'
  import Labour from '@/views/subcontractors/investigate/components/Labour'
  import { deleteTeamList } from '@/api/subcontractors/labour'
  import { getSubcontractorsLists } from '@/api/subcontractors'
  import {getOrgUsers ,getUsersDetail,getEmployeesList} from '@/api/commons';
  import {getlabourService  ,editlabourList} from '@/api/subcontractors/subcontractors'
  import {addfingernailList , getfingernailList,getServiceInformation ,deleteSub ,istheSameInvestigate} from '@/api/subcontractors/subcontractors'
  import { addInformatinService, editInformatinService} from '@/api/subcontractors/subcontractors'
  import { getLaborSubcontractors , getStatusCodeData} from '@/api/subcontractors/labor'
  import { addGroup ,editGroup, deleteGroup , getInvestigateMember,addMemberListsArr,deleteMemberListsArr} from '@/api/subcontractors/subcontractors'
  import  {getAllBranchCompany} from '@/api/commons'
  import { createValidTool } from '@/utils/regExpression'
  import Vue from 'vue'

  const columns = [
    {
      title: '序号',
      width:65,
      scopedSlots: { customRender: 'serial' }
    },
    {
      title: '姓名',
      dataIndex: 'employeeName',
      ellipsis: true,
    },
    {
      title: '职位',
      dataIndex: 'post',
      ellipsis: true,

    },
    {
      title: '类别',
      dataIndex: 'type',
      scopedSlots: { customRender: 'type' },
      ellipsis: true,

    },
    {
      title: '操作',
      dataIndex: 'action',
      scopedSlots: { customRender: 'action' }
    }
  ]
  const columns1 = [
    {
      title: '序号',
      width:65,
      scopedSlots: { customRender: 'serial' }
    },
    {
      title: '推荐分包商名称',
      dataIndex: 'recommendSubcontractors',
      ellipsis: true,
    },
    {
      title: '推荐人',
      dataIndex: 'recommend',
      ellipsis: true,
    },
    {
      title: '分公司',
      dataIndex: 'branchCompany',
      ellipsis: true,
    },
    {
      title: '推荐项目',
      dataIndex: 'recommendProject',
      ellipsis: true,
    },
    {
      title: '合作事项',
      dataIndex: 'cooperation',
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'isWarehousing',
      scopedSlots: { customRender: 'isWarehousing' }
    },
    // {
    //   title: '操作',
    //   dataIndex: 'action',
    //   scopedSlots: { customRender: 'action' }
    // }
  ]
  const columnsQul = [
    {
      title: '序号',
      width:65,
      dataIndex: 'name',
      scopedSlots: { customRender: 'serial' }
    },
    {
      title: '分包商名称',
      dataIndex: 'subcontractors',
      ellipsis: true,
    },
    {
      title: '分公司',
      dataIndex: 'branch',
      ellipsis: true,
    },
    {
      title: '分包商类型',
      dataIndex: 'type',
      ellipsis: true,
    },
    {
      title: '等级',
      dataIndex: 'level',
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'statusName',
    }
  ]
  // 数组创建时候的下标
  var numbe = 0

  export default {
  name:'a'+Date.now(),
    components: {
      Service,
      Fingernail,
      Labour,
    },
    props: {
      text: String,
      // 是否作为审批详情
      isAudit: {
        type: Boolean,
        default: false
      },
      // 是否作为意见征询
      isConsultation: {
        type: Boolean,
        default: false
      }
    },
    watch: {
      isAudit: {
        immediate: true,
        handler(val) {
            if (val) {
                this.type = 'view'
            }
        }
      }
    },

    data() {
      return {
        isValid:0, // 是否验证
        loadingState: {
          isRecomd: false,
          isQuality: false
        },
        qulSurveyId: '',//从合格分包商选择的带出来的考察id
        visible: false,
        qulVisible:false,
        isSubmitOrSave:'save',
        loading:false,
        loadings:false,
        nextSteps: '1',
        preStep:1,
        istheSameInvestigateType:false,//是否保存成功
        dataListQul:[],
        childValidInfo: createValidTool(), // 验证子组件信息
        confirmLoading:false,
        searchQueryQul:{},
        idAddEdit:0,//判断是新增的编辑还是编辑的编辑
        editTargetIndex: null, // 考察小组人员，编辑目标在表格中的序号
        searchQuery:{
        },
        subcontractorName:'',
        disabled:false,
        subcontractorId:"",
        selectDatas: {}, //
        columns,
        isSaveDraft:false,
        columns1,
        columnsQul,
        formAdd:{},
        list:[],
        editingKey: '',
        // 附件上传
        listUrl:'/cscec-project-business/subcontractors-file/inspect/query',
        deleteUrl:'/cscec-project-business/subcontractors-file/inspect/delete',
        uploadList:'/cscec-project-business/subcontractors-file/inspect/upload',
        reqMethod:'post',
        businessId:'',
        fileArrysDataList:[],
        title:'',
        labourList:{},
        pageSize:10,
        pageNumber:1,
        visibleGroup:false,
        fileList: [
          {
            uid: '-1',
            name: 'image.png',
            status: 'done',
            url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
          }
        ],
        headers: {
          authorization: 'authorization-text'
        },
        form:{ // 表单数据
          investigateType:'',
          list:[],
          subcontractorsType: []
        },
        status: 'all',
        employee:'',
        areaCode: '',
        basicList:{},
        dataList:[],
        ifReplace: null, // 是否替换小组成员
        type:false,
        groupLists:[],
        memberList:[],
        serviceList:{},
        typeList:[],
        fingernailList:{},
        id:'',
        subId:'', //分包商id
        designTypes:[ ],
        companyList:[],
        isCompany:false,
        isManager:false,
        selectedRows:[],
        selectedRowKeys: [],
        qulRecomSubselectedRowKeys:[],
        qulRecomSubselectedRows:[],
        RecomSubselectedRows:[],
        RecomSubselectedRowKeys: [],
        recommeddList:[],
        invesList:[],
        Modifyfield: {
          children: 'children',
          title: 'name',
          id: 'id',
        },
      }
    },
    created() {
      this.id = this.$route.query.id 
      this.type = this.$route.query.type
      if(this.$route.fullPath=='/project/subcontractors/investigate/view'){
        this.type='view'
      }
      const accessToken = this.$route.query.access_token
      if(accessToken){
        Vue.getAcloudProvider().setAccessToken(accessToken)
      }
      this.businessId = this.$route.query.id || this.id
      // if(this.type!='add'){
        this.getbasicInformation()
      // }
      this.getInvestigateType()
      this.getAllBranchCompany()
      if(this.type=='view'){
        this.confirmLoading = true
      }else{
        this.confirmLoading = false
      }
      // this.$refs.tabs.activeKey = this.nextSteps
      if(this.type=='add'){
        this.idAddEdit=0
      }else{
        this.idAddEdit=1
      }
    },
    methods: {
      fileArrysData(val) {
        this.fileArrysDataList = val
      },
      handleValidChanged(data) {
        this.childValidInfo.update(data)
      },
      getAllBranchCompany(){
        // this.loading=true
        getAllBranchCompany({tagCodes:['BC']}).then(res=>{
            this.companyList=res.data
            // this.loading=false
        })
      },
      // 保存考察信息草稿
      getsubmitNext(val){
        if(this.type!='view'){
          this.nextSteps='3'
          this.form.surveyId = this.id
          this.serviceList.investigateTypeCode = '1'
          // 当没有小组长时，不访问接口
          let groupLeader=this.memberList.filter(item=>item.type=='1')
          if(groupLeader.length!==0){
            editInformatinService(this.serviceList).then(res=>{
              if(res.code==200 || res.data.code == 200){
                this.businessId = res.data.investigateId
                this.getbasicInformation()
              }
            })
          }
        }else{
          this.nextSteps='3'
        }
      },
      // 甲指
      getsubmitNextSteps(val){
        if(this.type!='view'){
          this.nextSteps='3'
          this.fingernailList.investigateTypeCode = '2'
          editfingernailList(this.fingernailList).then(res=>{
            if(res.code==200 || res.data.code == 200){
              this.businessId = res.data.investigateId
              this.getbasicInformation()
              this.istheSameInvestigateType=true
            }
          })
        }else{
          this.nextSteps='3'
        }
      },
      // 劳务分包
      getsubmitNextStep(val){
        this.nextSteps='3'
        this.labourList.investigateId = this.id
        this.labourList.investigateTypeCode = '3'
        this.labourList.lsebId = this.labourList.subcontractorBase.evaluationId
        if(this.type!='view'){
          editlabourList(this.labourList).then(res=>{
            if(res.code==200 || res.data.code == 200){
              this.businessId = res.data.investigateId
              this.getbasicInformation()
              this.istheSameInvestigateType=true
            }
          })
        }
      },
      // 分包商类型
      getInvestigateType(){
        getInvestigateType({type:0}).then(res=>{
          this.invesList = res.data
        })
      },
      // 查询合格分包商
      getLaborSubcontractors(){
        if(this.loadingState.isQuality) return
        this.loadingState.isQuality = true
          getLaborSubcontractors({status:'0', ...this.searchQueryQul}).then(res=>{
            this.loadingState.isQuality = false
            this.dataListQul = res.data
          }).catch(() => {
            this.loadingState.isQuality = false
          })
      },
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      // 选择推荐分包商
      selectSub() {
        let arrs = []
        let arr = []
        if(this.RecomSubselectedRows.list){
          this.RecomSubselectedRows.list.forEach(item=>{
            arrs.push({id:item.id})
            arr.push(item.id)
          })
        }
        this.form = {
          ...this.form,
          list: arrs,
          subcontractorsType: arr,
          contractorId: this.RecomSubselectedRows.id,
          subcontractorName: this.RecomSubselectedRows.recommendSubcontractors,
          branchCompany: this.RecomSubselectedRows.branchCompany,
          branchCompanyId: this.RecomSubselectedRows.branchCompanyId,
          isQuality:  false
        }
        this.visible = false
        this.getAllBranchCompany()
      },
      // 确认合格分包商
      handleOkQul(){
        let arrs = []
        let arr = []
        if(this.qulRecomSubselectedRows.typeList){
          this.qulRecomSubselectedRows.typeList.forEach(item=>{
            arrs.push({id:item.id})
            arr.push(item.id)
          })
        }
        this.form = {
          ...this.form,
          list: arrs,
          subcontractorsType: arr,
          contractorId: this.qulRecomSubselectedRows.id,
          subcontractorName: this.qulRecomSubselectedRows.subcontractors,
          branchCompany: this.qulRecomSubselectedRows.branch,
          branchCompanyId: this.qulRecomSubselectedRows.branchId,
          isQuality: true,
          qulSurveyId:this.qulRecomSubselectedRows.surveyId, //合格分包商带出来的考察id,
          investigateType:this.qulRecomSubselectedRows.investigateType,
          ledgerId:this.qulRecomSubselectedRows.id
        }
        this.memberList = this.qulRecomSubselectedRows.memberList
        this.qulVisible = false
      },
      // 切换考察类型
      changeType(value){
        if(value=='1'){
          this.form.investigateType='服务类分包商考察'
          this.serviceList.subType = '服务类分包商考察'
        }else if(value=='2'){
          this.form.investigateType='甲指分包商考察'
          this.fingernailList.subType = '甲指分包商考察'
        }else if(value=='3'){
          this.form.investigateType='劳务/专业分包商考察'
          this.labourList.subType = '劳务/专业分包商考察'
        }
        if(this.form.investigateType==this.form.oldInvestigateType || !this.form.oldInvestigateType){
        }else{
          if(this.form.investigateType!=this.form.oldInvestigateType){
            this.$confirm({
              title: '警告提醒！',
              content: '如果切换，则已填写的考察信息将不再保存',
              okType: 'danger',
              onOk() {
                return false
              },
              onCancel() {
                return false
                  if(this.form.oldInvestigateType=='服务类分包商考察'){
                    this.form.oldInvestigateType='1'
                  }else if(this.form.oldInvestigateType=='甲指分包商考察'){
                    this.form.oldInvestigateType='2'
                  }else if(this.form.oldInvestigateType=='劳务/专业分包商考察'){
                    this.form.oldInvestigateType='3'
                  }
                this.$set(this.form,'investigateType',this.form.oldInvestigateType)
              },
            })
          }
        }
      },
      // 查询第一个tab页的详情
      getbasicInformation(){
        if(this.id){
          getbasicInformation({id:this.id}).then((res)=>{
            this.form = res.data
            const list = []
            this.form.typeList && this.form.typeList.forEach(item=>{
              list.push(item.name)
            })
            //fix- select placeholader未展示bug
            if(!this.form.investigateType){
              this.form.investigateType = undefined
            }
            if(!this.form.branchCompanyId){
              this.form.branchCompanyId = undefined
            }
            this.form = {
              ...this.form,
              subcontractorsType: list
            }
            this.memberList = this.form.memberList
          })
        }
      },
      employeeNums(val){
        this.employeeNum = val
      },

      // 从第一步到第二歩  验证必填项
      // 从第三歩到第二歩  不需验证必填项

      callback(key) {   // tabs切换
        let that = this
        that.nextSteps = key
          if(that.nextSteps == 2){
            if(that.form.investigateType=='服务类分包商考察'){
              // 服务
              getServiceInformation({id:that.id}).then((res)=>{
                that.serviceList = res.data
                that.serviceList.subcontractorId = resItem.data.subcontractorId
                that.serviceList.subType = "服务类分包商考察"
              })
            }
            // 甲指
            if(that.form.investigateType=='甲指分包商考察'){
              getfingernailList({id:that.id}).then((res)=>{
                that.fingernailList = res.data
                that.fingernailList.subcontractorId = resItem.data.subcontractorId
                that.fingernailList.subType = "甲指分包商考察"
              })
            }
            // 劳务
            if(that.form.investigateType=='劳务/专业分包商考察'){
              getlabourService({id:that.id}).then((res)=>{
                that.labourList = res.data
                that.labourList.subcontractorId = resItem.data.subcontractorId
                that.labourList.subType = "劳务/专业分包商考察"
              })
            }
          }
      },
      getPopupContainer(triggerNode){
        return  triggerNode.parentNode
      },
      handleCancel() {
        this.visible = false
      },
      handleCancelQul(){
        this.qulVisible = false
      },
      nextStep() {
        // 下一步
        let that = this
          let steps = that.nextSteps
        // if(that.type=='view' || type!='approve'){
          if(steps == '1'){
            that.nextSteps = '2'
            if(that.form.investigateType=='服务类分包商考察'){
              // 服务
              getServiceInformation({id:that.id}).then((res)=>{
                that.serviceList = res.data
                that.serviceList.subcontractorId = resI.data.subcontractorId
              })
            }
            // 甲指
            if(that.form.investigateType=='甲指分包商考察'){
              getfingernailList({id:that.id}).then((res)=>{
                that.fingernailList = res.data
                that.fingernailList.subcontractorId = resItem.data.subcontractorId
              })
            }
            // 劳务
            if(that.form.investigateType=='劳务/专业分包商考察'){
              getlabourService({id:that.id}).then((res)=>{
                that.labourList = res.data
                that.labourList.subcontractorId = resItem.data.subcontractorId
              })
            }
          }else if(steps =='2'){
            that.nextSteps = '3'
          }
        // }
      },
      goBack(){
        window.close()
      },
      getOrgUsers(val){
        // this.loading = true
        // let companyId  = JSON.parse(sessionStorage.getItem('ycloud-user_info')).orgId
        // getEmployeesList({queryPostRelation:true,pageNo:1,pageSize:10}).then(res=>{
        //   this.groupLists = res.data
        //   // this.loading = false
        // })
      getEmployeesList({key:val?val:'',pageNumber:this.pageNumber,pageSize:this.pageSize1}).then((res) => {
        if(res.data){
          let data = []
          res.data && res.data.forEach(item => {
            if (!this.groupLists.filter(itemc => item.id == itemc.id).length) {
              data.push(item)
            }
          })
          this.groupLists  = this.groupLists.concat(data)
        }
        this.totalPages = res.totalPages
        this.totalSize1 = res.totalSize
      })
      },
    }
  }
</script>

<style lang="less" scoped>
  .wrapper-row {
    padding-left: 55px;
    font-weight: bold;
    letter-spacing: 1px;
  }

  /deep/ .ant-form-item label {
    font-size: 12px;
  }

  /deep/ .ant-btn {
    border-radius: 5px;
  }

  // /deep/ .ant-calendar-picker-input.ant-input {
  //   width: 100%;
  // }

  /deep/ .ant-input {
    /*width: 70%;*/
    border-radius: 5px;
  }

  // /deep/ .ant-calendar-picker {
  //   width: 100%;
  //   border-radius: 5px;
  // }

  /deep/ .ant-card.ant-card-bordered {
    border-radius: 5px;
  }

  .ant-avatar-lg {
    width: 48px;
    height: 48px;
    line-height: 48px;
  }

  .list-content-item {
    color: rgba(0, 0, 0, 0.45);
    display: inline-block;
    vertical-align: middle;
    font-size: 14px;
    margin-left: 40px;
    span {
      line-height: 20px;
    }
    p {
      margin-top: 4px;
      margin-bottom: 0;
      line-height: 22px;
    }
  }

  .title-name {
    border-left: 5px solid #1890ff;
    font-weight: bold;
    font-size: 16px;
    margin-bottom: 20px;
    padding-left: 15px;
    height: 20px;
    line-height: 20px;
  }

  /deep/ .table-page-search-wrapper .ant-form-inline .ant-row .ant-col.ant-col-sm-24.ant-col-md-12 {
    padding-left: 80px;
  }
  /deep/ .ant-card-bordered{
    margin-top:60px
  }
  /deep/ .ant-table-pagination.ant-pagination{
    display:none
  }
</style>

